import env from "../../../../utils/env";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    // 搜索
    serach_pro: "",
    prosum: null,
    oriProlist: [],
    prolist: [
      // {
      //   bankId: '',
      //   bankName: '全部分支行'
      // }
    ],
    loading: true,
    showSelect: false,
    typeName: '全选',
    bankId: '',
    bankIds: [],
    FilePath: '',
    beginDate: '',
    endDate: '',
    FilePath: ''
  },
  goOnChange (e) {
    this.setData({
      serach_pro: e.detail,
    });
  },
  selectAll (e) {
    if (e.currentTarget.dataset.key === '全选') {
      this.data.prolist.forEach(pre => pre.show = true)
      this.setData({
        typeName: '取消全选',
        prolist: this.data.prolist
      })
    } else {
      this.data.prolist.forEach(pre => pre.show = false)
      this.setData({
        typeName: '全选',
        prolist: this.data.prolist
      })
    }

  },
  async openMethod () {
    // 统计所有选择的支行
    // this.data.prolist.forEach(val => {
    //   if (val.show) {
    //     this.data.bankIds.push(val.bankId)
    //   }
    // })
    const needList = this.data.prolist.filter(val => val.show)
    if (needList.length === 0) {
      wx.showToast({
        title: "请至少选择一家银行进行导出",
        icon: 'none'
      })
    } else {
      const res = await this.download(needList)
      setTimeout(function () {
        wx.hideLoading();
      }, 200);
      this.setData({
        showSelect: true,
      });
    }
    // console.log(this.data.bankIds, 'bankIds')
  },
  async downloadWx () {
    const _this = this
    // const res = await _this.download()
    // console.log(res, '下载最后')
    wx.shareFileMessage(
      {
        filePath: _this.data.FilePath,
        fileName: '营销统计信息.xlsx',
        success (data) {
          _this.hideSelect()
        },
        fail (res) {
          console.log(res, '分享报错的原因')
          // wx.showToast({
          //   title: JSON.stringify(res),
          //   icon: "none"
          // })
        }
      }
    )
  },
  download (list) {
    wx.showLoading({
      title: "导出中...",
    });
    const _this = this
    console.log(list, '导出的传参')
    return new Promise(function (resolve, reject) {
      wx.request({
        // url: 'http://192.168.1.200:20100/boc/exportOverview',
        // url: 'http://192.168.1.191:20100/boc/exportOverview',
        url: env.baseUrl + '/boc/exportOverview',
        data: list,
        method: 'POST',
        header: {
          "content-type": "application/json",
          "token": wx.getStorageSync('token')
        },
        responseType: "arraybuffer", //注意这里的responseType
        success: (result) => {
          let fileManager = wx.getFileSystemManager();
          _this.data.FilePath = wx.env.USER_DATA_PATH + "/" + 'zx' + '-' + '测试.xlsx';
          console.log(_this.data.FilePath, 'FilePath')
          fileManager.writeFile({
            data: result.data,
            filePath: _this.data.FilePath,
            encoding: "binary", //编码方式 
            success: res => {
              console.log("下载成功！", result);
              resolve('1111')
              // wx.openDocument({ //我这里成功之后直接打开
              //   filePath: FilePath,
              //   showMenu: true,
              //   fileType: "xls",
              //   success: result => {
              //     this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档成功");
              //   },
              //   fail: err => {
              //     this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档失败", err);
              //   }
              // });
              // // 分享给好友
              // wx.shareFileMessage(
              //   {
              //     filePath: FilePath,
              //     fileName: '测试.xls',
              //     success (data) {
              //       _this.hideSelect()
              //     },
              //     fail (res) {
              //       wx.showToast({
              //         title: JSON.stringify(res),
              //         icon: "none"
              //       })
              //     }
              //   }
              // )
            },
            fail: res => {
              wx.showToast({
                title: '下载失败!',
                icon: 'none', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 2000, //停留时间
              })
            }
          })
        },
        fail (err) {
          console.log(err)
        }
      })
    })

  },
  hideSelect () {
    this.setData({
      showSelect: false,
    });
  },
  selectOne (e) {
    // console.log(e.currentTarget.dataset.name, 'eee')
    const oriProlistIndex = this.data.oriProlist.findIndex(val => val.bankName === e.currentTarget.dataset.name)
    const prolistIndex = this.data.prolist.findIndex(val => val.bankName === e.currentTarget.dataset.name)
    if (oriProlistIndex > -1) {
      this.data.oriProlist[oriProlistIndex].show = !this.data.oriProlist[oriProlistIndex].show
    }
    if (prolistIndex > -1) {
      this.data.prolist[prolistIndex].show = !this.data.prolist[prolistIndex].show
    }
    this.setData({
      oriProlist: this.data.oriProlist,
      prolist: this.data.prolist
    })

  },
  goSearch () {
    let prolist = JSON.parse(JSON.stringify(this.data.oriProlist)).filter(
      d =>
        d.name &&
        (d.name.indexOf(this.data.serach_pro.toLowerCase()) !== -1 ||
          d.name.indexOf(this.data.serach_pro.toUpperCase()) !== -1)
    );
    this.setData({
      prolist: prolist
    })
    // console.log(this.data.prolist, 'prolist')
  },
  goCopy () {
    let that = this;
    wx.setClipboardData({
      data: "www.baidu.com",
      success (res) {
        that.hideSelect();
        wx.showToast({
          title: "链接已复制",
          icon: "none",
        });
      },
    });
  },
  toprodetail (e) {
    // console.log(e.detail, "e.detail");
    if (e.detail.totalscore || e.detail.totalscore == 0) {
      wx.navigateTo({
        url:
          "/packageA/pages/homelink/measure_limit_detail/measure_limit_detail?corpKey=" +
          e.detail.corpKey,
      });
    } else {
      wx.showToast({
        title: "该企业尚未进行地方征信平台授权，请提交授权书后使用测额度功能",
        icon: "none",
      });
    }
  },
  // 滑动底部加载更多
  scrollBottom () {
    // this.onBottom();
  },
  getList () {
    var _this = this;
    this.setData({
      loading: true,
    });
    wx.showLoading({
      title: "加载中",
    });
    // const params = {
    //   pageSize: 50,
    //   pageNum: this.data.pageNum,
    //   keyword: _this.data.serach_pro,
    // };
    const params = {
      // bankId: this.data.bankId,
      name: _this.data.serach_pro,
      beginDate: _this.data.beginDate,
      endDate: _this.data.endDate
    };
    let url = ''
    if (this.data.bankId) {
      url = '/boc/getLevel2Overview'
      params.bankId = this.data.bankId
    } else {
      url = '/boc/getOverview'
    }
    console.log(params, "params1111111111");
    getApp()
      .globalData.request(url, params, "POST")
      .then((res) => {
        setTimeout(function () {
          wx.hideLoading();
        }, 500);
        let rstObj = res;
        console.log(res, "res");
        if (rstObj.data) {
          rstObj.data.forEach(element => {
            element.show = false
          });
          _this.setData({
            oriProlist: JSON.parse(JSON.stringify(rstObj.data)),
            prolist: JSON.parse(JSON.stringify(rstObj.data)),
            // prosum: rstObj.data.total,
          });
          this.setData({
            loading: false,
          });
        }
      });
  },

  onBottom () {
    if (this.data.prolist.length >= this.data.prosum) return;
    this.data.pageNum++;
    this.getList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    this.setData({
      bankId: options.bankId || '',
      beginDate: options.beginDate,
      endDate: options.endDate
    })
    // const list = [{
    //   name: '苏州银行'
    // }, {
    //   name: '中国银行'
    // }]
    // this.setData({
    //   prolist: list,
    //   prosum: 2
    // })
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () { },
});
